package rbac_api

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gvalid"
)

type userSaveReq struct {
	Email string `p:"email"`
	Tel   string `p:"tel"`
	Name  string `p:"name"`
	Id    string `p:"id"`
}

type userSaveRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

type userSaveOrm struct {
	Email string `orm:"email"`
	Tel   string `orm:"tel"`
	Name  string `orm:"name"`
}

func (a *userApi) Save(r *ghttp.Request) {
	var req *userSaveReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(userSaveRes{
			Code: 0,
			Msg:  err.Error(),
		})
	}
	//输入参数校验
	rules := map[string]string{
		"email": "required|length:1,16",
		"name":  "required|length:1,16",
		"tel":   "required|length:1,16",
	}
	msgs := map[string]interface{}{
		"email": map[string]string{
			"required": "邮箱不能为空",
			"length":   "邮箱长度太长",
		},
		"name": map[string]string{
			"required": "姓名不能为空",
			"length":   "姓名长度太长",
		},
		"tel": map[string]string{
			"required": "电话不能为空",
			"length":   "电话长度太长",
		},
	}

	if e := gvalid.CheckMap(req, rules, msgs); e != nil {
		r.Response.WriteJsonExit(userSaveRes{
			Code: 0,
			Msg:  e.String(),
		})
	}
	m0, err := g.DB().Model("user").Where("email=?", req.Email).Where("id<>?", req.Id).One()
	if err == nil {
		if !m0.IsEmpty() {
			r.Response.WriteJsonExit(userSaveRes{
				Code: 0,
				Msg:  "邮箱已存在",
			})
		}
	}
	var userSaveOrm userSaveOrm
	userSaveOrm.Tel = req.Tel
	userSaveOrm.Email = req.Email
	userSaveOrm.Name = req.Name

	_, err = g.DB().Model("user").Data(userSaveOrm).Where("id=?", req.Id).Update()
	if err != nil {
		r.Response.WriteJsonExit(userSaveRes{
			Code: 0,
		})
	}

	r.Response.WriteJsonExit(userSaveRes{
		Code: 1,
	})
}
